<template>
  <pc-nav></pc-nav>
<!--  <bread v-if="siteBar.type" :sitebar="siteBar.data"></bread>-->
  <div class="container" style="background:none; margin: 0 auto; padding: 0; padding-top:20px;">
    <view>
      <s-layout-pc navbar="none">
        <!-- 骨架屏 -->
        <detailSkeleton v-if="state.skeletonLoading" />
        <!-- 标题栏 -->
        <!-- 下架/售罄提醒 -->
        <s-empty v-else-if="state.goodsInfo === null" text="商品不存在或已下架" icon="/static/soldout-empty.png" showAction
                 actionText="再逛逛" actionUrl="/pages/goods/list" />
        <block v-else>
          <!--商品标题-->
          <!--      <detailNavbar v-if="state.goodsInfo.sku_prices.length>0" />
                    <detailNavbarone v-if="state.goodsInfo.sku_prices.length==1" />-->
          <div class="container">
          <view class="detail-swiper-selector d-flex">

              <!-- 商品轮播图  -->
              <su-swiper-pc style="width:400px;height:300px;flex-shrink:0" class="ss-m-b-14" isPreview :list="state.goodsSwiper" dotStyle="tag" imageMode="scaleToFit"
                            dotCur="bg-mask-40" :seizeHeight="750" />

              <view class="right-box ss-flex-grow-1" style="width:100%;">
                <!-- 价格 -->
                <view class="title-card detail-card ss-p-x-20">
                  <view class="title-text ss-line-2 ss-m-b-6">{{ state.goodsInfo.title }}</view>
                  <view class="subtitle-text ss-line-1" v-if="state.goodsInfo.subtitle">{{ state.goodsInfo.subtitle }}</view>

                  <view class="ss-m-y-10 price-box-wrapper">
                    <view class="price-box ss-flex ss-col-bottom ss-m-b-30">
                      <view class="price-text ss-m-r-16" v-if="state.selectedPriceAll > 0">
                        {{ state.selectedPriceAll }}
                      </view>
                      <view class="price-text ss-m-r-16" v-else>
                        {{ state.selectedSkuPrice.price || formatPrice(state.goodsInfo.price) }}
                        {{Number(state.goodshighprice)>Number(state.goodsInfo.price)?`~${state.goodshighprice}`:''}}
                      </view>
                      <view class="origin-price-text" v-if="state.selectedOriginalPriceAll > 0">
                        {{ state.selectedOriginalPriceAll }}
                      </view>
                      <view class="origin-price-text" v-else-if="state.goodsInfo.original_price > 0">
                        {{ state.selectedSkuPrice.original_price || state.goodsInfo.original_price }}
                      </view>
                    </view>
                    <detail-cell-service-pc v-if="state.goodsInfo.service" v-model="state.goodsInfo.service" :no-popup="true" />
                  </view>
                  <view class="discounts-box ss-flex ss-row-between">
                    <view class="tag-content">
                      <view class="tag-box ss-flex">
                        <view class="tag ss-m-r-10" v-for="promos in state.goodsInfo.promos"
                              :key="promos.id" @tap="onActivity">
                          {{ promos.title }}
                        </view>
                      </view>
                    </view>
                  </view>
                  <s-coupon-get-pc class="ss-m-b-20" v-model="state.couponInfo" @get="onGetCoupon" />
                </view>

                <!-- 功能卡片 -->
                <view class="detail-cell-card detail-card ss-flex-col" v-if="state.goodsInfo.sku_prices.length>1">
                  <s-select-sku-pc :goodsInfo="state.goodsInfo" @change="onSkuChange" @selectChange="onSkuSelectChange" />
                </view>
                <view class="detail-cell-card detail-card ss-flex-col p-3">
                  <!-- 详情tabbar -->
                  <view :cart_num="state.cart_num">
                    <!-- TODO: 缺货中 已售罄 判断 设计-->
                    <view class="buy-box ss-flex ss-col-center ss-p-r-20" v-if="state.goodsInfo.stock > 0">
                      <view class="buy-box ss-flex ss-col-center ss-flex ss-col-center ss-row-center">
                        <button  class="ss-reset-button add-btn ui-Shadow-Main" @tap="onAddCart()">
                          加入购物车
                        </button>
                        <button v-if="state.goodsInfo.sku_prices.length>1" class="ss-reset-button buy-btn ui-Shadow-Main" @tap="onBuy_duo">
                          立即购买
                        </button>
                        <button v-if="state.goodsInfo.sku_prices.length==1" class="ss-reset-button buy-btn ui-Shadow-Main" @tap="onBuy_dan(state.goodsInfo.sku_prices[0])">
                          立即购买
                        </button>
                        <view style="width:60px"></view>
                        <view class="position-relative ss-flex cart" @click="sheep.$router.go('/pages/index/cart')">
                          <image src="/static/cart.png" class="cart-icon"></image>
                          <view class="position-absolute cart-num">{{ state.cart_num }}</view>
                        </view>
                      </view>
                    </view>
                    <view class="buy-box ss-flex ss-col-center ss-p-r-20" v-else>
                      <button class="ss-reset-button disabled-btn" disabled>已售罄</button>
                    </view>
                  </view>
                </view>
              </view>
          </view>
          </div>

          <!-- 详情 -->
          <view class="container detail-box">
            <view class="detail-tabs">
              <view class="tabs-header ss-flex">
                <view 
                  v-for="(tab, index) in state.tabs" 
                  :key="index"
                  class="tab-item"
                  :class="{'active': state.currentTab === index}"
                  @click="switchTab(index)"
                >
                  {{tab.name}}{{ index === 2 && state.commentTotal > 0 ? `(${state.commentTotal})` : '' }}
                </view>
              </view>
              
              <view class="tabs-content" style="height: auto !important;">
                <!-- 商品详情 -->
                <view v-show="state.currentTab === 0">
                  <detail-content-card-pc class="detail-content-selector" :content="state.goodsInfo.content" />
                </view>
                
                <!-- 课程大纲 -->
                <view v-show="state.currentTab === 1">
                  <detail-dagang-card-pc v-if="state.goodsInfo.sku_prices.length>1" class="detail-dagang-selector" :goodsId="state.goodsId" />
                </view>
                
                <!-- 评价 -->
                <view v-show="state.currentTab === 2">
                  <detail-comment-card-pc class="detail-comment-selector" :goodsId="state.goodsId" @totalCount="onGetCommentTotalCount" />
                </view>
              </view>
            </view>
            <s-goods-recommend />
          </view>


          <!-- 活动跳转 -->
          <detail-activity-tip v-if="state.goodsInfo.activities" :data="state.goodsInfo"></detail-activity-tip>

          <s-activity-pop-pc v-model="state.activityInfo" :show="state.showActivityModel"
                             @close="state.showActivityModel = false" />
        </block>

      </s-layout-pc>

    </view>

  </div>
  <div class="container-fluid">
    <pc-footer></pc-footer>
  </div>
</template>

<script setup>
  import {
    reactive,
    computed
  } from 'vue';
  import {
    onLoad,
    onShow,
    onPageScroll
  } from '@dcloudio/uni-app';
  import sheep from '@/sheep';
  import { showAuthModal } from '@/sheep/hooks/useModal';
  import {
    formatGoodsSwiper,
    formatPrice
  } from '@/sheep/hooks/useGoods';
  import detailCellServicePc from './components/detail/detail-cell-service-pc.vue';
  import detailSkeleton from './components/detail/detail-skeleton.vue';
  import detailCommentCardPc from './components/detail/detail-comment-card-pc.vue';
  import detailContentCardPc from './components/detail/detail-content-card-pc.vue';
  import detailDagangCardPc  from './components/detail/detail-dagang-card-pc.vue';
  import detailActivityTip from './components/detail/detail-activity-tip.vue';
  import {
    isEmpty
  } from 'lodash';
  import pcNav from '@/sheep/components/pc-nav/pc-nav.vue';
  import Bread from '@/sheep/components/bread/bread.vue';
  import pcFooter from '@/sheep/components/pc-footer/pc-footer.vue';
  import SLayout from '@/sheep/components/s-layout/s-layout.vue';
  const cart = sheep.$store('cart');

  onPageScroll(() => {});
  const siteBar=reactive({
    type:true,
    data:[{
      name:'首页',
      url:'/pages/index/index',
    },
      {
        name:'课程列表',
        url:'/pages/goods/list',
      }
    ]
  });
  const state = reactive({
    goodsId: 0,
    skeletonLoading: true,
    goodsInfo: {},
    showSelectSku: false,
    goodsSwiper: [],
    selectedSkuPrice: {},
    showModel: false,
    total: 0,
    couponInfo: [],
    showActivityModel: false,
    activityInfo: [],
    list: computed(() => cart.list),
    cart_num: 0,
    goodshighprice:0,
    selectedOriginalPriceAll:0,
    selectedPriceAll:0,
    selectedSkus: [],
    tabs: [
      { name: '商品详情' },
      { name: '免费试听' },
      { name: '评价' }
    ],
    currentTab: 0,
    commentTotal: 0,
  });

  function onGetCommentTotalCount(total){
    state.commentTotal = total;
  }

  function switchTab(index){
    state.currentTab = index;
  }

  // 规格变更
  function onSkuChange(e) {
    state.selectedSkuPrice = e;
  }

  function onSkuSelectChange(e) {
    state.selectedOriginalPriceAll = e.originalPrice;
    state.selectedPriceAll = e.price;
    state.selectedSkus = e.skus;
  }

  // 添加购物车
  function onAddCart() {
    if(state.goodsInfo.sku_prices.length>1){
      if (state.selectedSkus.length === 0) {
        sheep.$helper.toast('请选择商品');
        return;
      }
      state.selectedSkus.forEach((sku) => {
        state.goodsInfo.sku_prices.forEach((item)=>{
          if(sku==item.goods_sku_ids)
          {
            if (item.goods_id) {
              if (item.stock <= 0) {
                sheep.$helper.toast('库存不足');
              } else {
                sheep.$store('cart').add(state.goodsInfo.sku_prices[0]).then(()=>{
                  setTimeout(getCartNum, 500);
                });
              }
            } else {
              sheep.$helper.toast('请选择规格');
            }
          }
        });
      });
    }else{
      //直接加入购物车
      sheep.$store('cart').add(state.goodsInfo.sku_prices[0]).then(()=>{
        setTimeout(getCartNum, 500);
      });
    }
  }

  async function getCartNum1()
  {
    var totalNum = 0;
    let data= await sheep.$store('cart').getListnew();
    var cartlist = data.list;
    for (var i = 0; i < cartlist.length; i++) {
      totalNum += cartlist[i].goods_num;
    }
    state.cart_num = totalNum;
  }

  //获取购物车数量
  function getCartNum(){
    var totalNum = 0;
    for (var i = 0; i < state.list.length; i++) {
      totalNum += state.list[i].goods_num;
    }
    state.cart_num = totalNum;
  }

  function onBuy_duo() {
    let goods_list = [];
    //yisha
    state.selectedSkus.forEach((sku) => {
      state.goodsInfo.sku_prices.forEach((item)=>{
        if(sku==item.goods_sku_ids)
        {
          goods_list.push({
            goods_id: item.goods_id,
            goods_num: 1,
            goods_sku_price_id: item.id,
          });

        }
      });
    });
    if (goods_list.length === 0) {
      sheep.$helper.toast('请选择商品');
      return;
    }

    sheep.$store('user').getInfo()
      .then((resinfo) => {
        //if(1)
        if(resinfo.mobile)
        {
          sheep.$router.go('/pages/order/confirm', {
            data: JSON.stringify({
              order_type: 'goods',
              goods_list,
              from: 'cart',
            }),
          });
        }
        else
        {
          sheep.$store('modal').$patch((state) => {
            state.auth = '';
            setTimeout(() => {
              showAuthModal('changeMobile');
            }, 100);

          });

        }

      });
  }

  // 立即购买
  function onBuy_dan(e) {
    sheep.$store('user').getInfo()
      .then((resinfo) => {
          //if(1)
          if(resinfo.mobile)
          {
            sheep.$router.go('/pages/order/confirm', {
              data: JSON.stringify({
                order_type: 'goods',
                goods_list: [{
                  goods_id: e.goods_id,
                  goods_num: 1,
                  goods_sku_price_id: e.id,
                }, ],
              }),
            });
          }
          else
          {
            sheep.$store('modal').$patch((state) => {
              state.auth = '';
              setTimeout(() => {
                showAuthModal('changeMobile');
              }, 100);

            });
          }
        }
      );
  }
  //营销活动
  function onActivity() {
    state.activityInfo = state.goodsInfo.promos;
    state.showActivityModel = true;
  }

  async function getCoupon(){
    const {
      code,
      data
    } = await sheep.$api.coupon.listByGoods(state.goodsId);
    if (code === 1) {
      state.couponInfo = data;
    }
  }

  //立即领取
  async function onGetCoupon(id) {
    const {
      code,
      msg
    } = await sheep.$api.coupon.get(id);
    if (code === 1) {
      uni.showToast({
        title: msg,
      });
      setTimeout(() => {
        getCoupon();
      }, 1000);
    }
  }

  const shareInfo = computed(() => {
    if (isEmpty(state.goodsInfo)) return {};
    return sheep.$platform.share.getShareInfo({
      title: state.goodsInfo.title,
      image: sheep.$url.cdn(state.goodsInfo.image),
      desc: state.goodsInfo.subtitle,
      params: {
        page: '2',
        query: state.goodsInfo.id,
      },
    }, {
      type: 'goods', // 商品海报
      title: state.goodsInfo.title, // 商品标题
      image: sheep.$url.cdn(state.goodsInfo.image), // 商品主图
      price: state.goodsInfo.price[0], // 商品价格
      original_price: state.goodsInfo.original_price, // 商品原价
    }, );
  });

  onShow(async (options) => {
    setTimeout(getCartNum, 200);
  });

  onLoad(async (options) => {
    // 非法参数
    if (!options.id) {
      state.goodsInfo = null;
      return;
    }

    setTimeout(getCartNum, 200);

    state.goodsId = options.id;
    // 加载商品信息
    sheep.$api.goods.detail(state.goodsId).then((res) => {
      state.skeletonLoading = false;
      if (res.code === 1) {
        state.goodsInfo = res.data;

        state.goodsInfo.sku_prices.forEach((item)=>{
          if(Number(state.goodshighprice)<=Number(item.price))
          {
            state.goodshighprice=item.price
          }
        });
        state.goodsSwiper = formatGoodsSwiper(state.goodsInfo.images);

      } else {
        // 未找到商品
        state.goodsInfo = null;
      }

    });

    getCoupon();
    cart.getList().then(getCartNum);

    setTimeout(function() {
      var elements = document.getElementsByClassName('uni-video-cover-play-button');
      if (elements.length > 0) {
        elements[0].click();
      } else {
        console.log('没有找到具有类名 "uni-video-control-button-play" 的元素');

      }
    }, 1200);
    setTimeout(function() {
      var elements = document.getElementsByClassName('uni-video-control-button-play');
      if (elements.length > 0) {
        elements[0].click();
      } else {
        console.log('没有找到具有类名 "uni-video-control-button-play" 的元素');

      }
    }, 1500);
  });
</script>

<style lang="scss" scoped>
  .detail-content-card
  {
    .card-header{
    .title{ font-size: 48rpx;
    }
    }
  }
  .page-app:after {
    content: '';
    display: block;
    clear: both;
  }

  .detail-card {
    background-color: #ffff;
    margin: 0 20rpx;
    border-radius: 10rpx;
    overflow: hidden;
  }

  // 价格标题卡片
  .title-card {
    .price-box-wrapper {
      padding: 15px 10px 5px 15px;
      background-color: #f9f9f9;
    }

    .price-box {
      .price-text {
        font-size: 42rpx;
        font-weight: 500;
        color: #ff3000;
        line-height: 30rpx;
        font-family: OPPOSANS;

        &::before {
          content: '￥';
          font-size: 30rpx;
        }
      }

      .origin-price-text {
        font-size: 26rpx;
        font-weight: 400;
        text-decoration: line-through;
        color: $gray-c;
        font-family: OPPOSANS;

        &::before {
          content: '￥';
        }
      }
    }

    .sales-text {
      font-size: 26rpx;
      font-weight: 500;
      color: $gray-c;
    }

    .discounts-box {
      .tag-content {
        flex: 1;
        min-width: 0;
        white-space: nowrap;
      }

      .tag-box {
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .tag {
        flex-shrink: 0;
        padding: 4rpx 10rpx;
        font-size: 24rpx;
        font-weight: 500;
        border-radius: 4rpx;
        color: var(--ui-BG-Main);
        background: var(--ui-BG-Main-tag);
      }

      .discounts-title {
        font-size: 24rpx;
        font-weight: 500;
        color: var(--ui-BG-Main);
        line-height: normal;
      }

      .cicon-forward {
        color: var(--ui-BG-Main);
        font-size: 24rpx;
        line-height: normal;
        margin-top: 4rpx;
      }
    }

    .title-text {
      font-size: 24px;
      font-weight: bold;
      line-height: 36px;
    }

    .subtitle-text {
      font-size: 14px;
      font-weight: 400;
      color: $dark-9;
      line-height: 24px;
      margin-bottom: 30px;
    }
  }

  // 购买
  .buy-box {
    .add-btn {
      width: 284rpx;
      height: 72rpx;
      font-weight: 500;
      font-size: 28rpx;
      background-color: var(--ui-BG-Main-light);
      color: var(--ui-BG-Main);
    }

    .buy-btn {
      width: 284rpx;
      height: 72rpx;
      font-weight: 500;
      font-size: 28rpx;
	    margin-left: 26px;
      background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
      color: $white;
    }

    .disabled-btn {
      width: 428rpx;
      height: 72rpx;
      font-weight: 500;
      font-size: 28rpx;
      border-radius: 0 40rpx 40rpx 0;
      background: linear-gradient(90deg, var(--ui-BG-Main), var(--ui-BG-Main-gradient));
      color: $white;
    }
  }

  .model-box {
    height: 60vh;

    .model-content {
      height: 56vh;
    }

    .title {
      font-size: 36rpx;
      font-weight: bold;
      color: #333333;
    }

    .subtitle {
      font-size: 26rpx;
      font-weight: 500;
      color: #333333;
    }
  }

  .detail-tabs {
    flex-grow: 1;
    background: #fff;
    
    .tabs-header {
      .tab-item {
        padding: 20rpx 40rpx;
        font-size: 28rpx;
        color: #666;
        position: relative;
        cursor: pointer;
        
        &.active {
          color: var(--ui-BG-Main);
          font-weight: bold;
          
          &:after {
            content: '';
            position: absolute;
            left: 50%;
            bottom: -2rpx;
            transform: translateX(-50%);
            width: 40rpx;
            height: 4rpx;
            background: var(--ui-BG-Main);
            border-radius: 2rpx;
          }
        }
      }
    }
    
    .tabs-content {
      min-height: 300px;
      &:after {
        content: '';
        display: block;
        clear: both;
      }
    }
  }

  .cart {
    cursor: pointer;
  }

  .cart-icon {
    width: 24px;
    height: 24px;
  }

  .cart-num {
    position: absolute;
    top: -5px;
    right: -8px;
    font-size: 12px;
    width: 20px;
    height: 14px;
    background: var(--ui-BG-Main);
    border-radius: 10px;
    color: #fff;
    text-align: center;
    line-height: 14px;
  }

  .detail-box {
    display: flex;
    justify-content: space-between;
    gap: 20px;
  }

</style>